<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {


	public function test(){
		echo "1";
	}

	public function index() {

		$AppID = 'wx9530539921dbc2d7';
		$AppSECRET = '6f5a22cf8a8e144f3d3844cf9c821ffd';
		$info = "";

		if (isset($_REQUEST['code'])) {

			$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $AppID . '&secret=' . $AppSECRET . '&code=' . $_REQUEST['code'] . '&grant_type=authorization_code';

			$html = file_get_contents($url);
			$info = json_decode($html);

		} else {
			$reurl = urlencode(get_url());
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $AppID . '&redirect_uri=' . $reurl . '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			header('location: ' . $url);
                        
			exit ;
		}
		if ($info -> openid == null)
			$this -> error("获取openid失败,请勿刷新网页", U("index/index"), 2);
		$this -> assign("openid", $info -> openid);
		$this -> display();

	}

	public function shaked() {
		
		header("Content-type: text/html; charset=utf-8");

		if (I("openid") == "") {
			echo err_0;
			//获取openid失败
			exit ;
		}

		if (rand(1,1) == 1) {
		
		
		$bonus = M("bonus");
		$bonus->startTrans();
		$code = $bonus->order("rand()")->field('id','code','money')->find();
		if($code==null)
		  {echo "红包已经派完";exit;}
		$bonus->delete($code['id']);
		$bonus->commit();
		
		$box = array();
		$box['nonce_str'] = "auto";
		$box['mch_billno'] =$code['code'];
		$box['mch_id'] = "1262724001";
		$box['wxappid'] = "wx9530539921dbc2d7";
		$box['send_name'] = "盈信创展";
		$box['re_openid'] = I("openid");
		$box['total_amount'] = $code['money'];
		$box['total_num'] = 1;
		$box['wishing'] = "感谢您参加摇一摇活动，祝你中秋节快乐";
		$box['client_ip'] = "113.107.140.156";
		$box['act_name'] = "中秋摇一摇抢红包活动";
		$box['remark'] = "只需摇一摇，红包得手，快来抢！";
		ksort($box);
		$stringA = "";
		foreach ($box as $key => $value) {
			$stringA = $stringA . $key . "=" . $value . "&";
		}
		$stringA .= "key=jm0750yxcz1688dayofthesun0906214";
		$stringA = md5($stringA);
		$sign = strtoupper($stringA);
		$box['sign'] = $sign;
		$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
		$xml = array2xml($box);

				$xml=simplexml_load_string(curl_post_ssl($url,$xml));
		
				if(strval($xml->return_msg)=="发送成功")
				{echo "获得".($code['code']/100)."元";
				exit; }
				else
					{
						dump(strval($xml->return_msg));
					}
		} 
		else {
			echo "没中";
			exit ;
		}

		

	}

}
